var Clue = function(){

	return {
    	init: function () {
			var track_form = $('#track_form');

			// 表单验证
			track_form.validate({
				errorElement: 'span', //default input error message container
				errorClass: 'help-block', // default input error message class
				focusInvalid: false, // do not focus the last invalid input
				ignore: "",
				rules: {
					track_wish: {
						digits: true,
					},
					track_result: {
						required: true,
					},
					track_date: {
						required: true,
					},

				},

				invalidHandler: function (event, validator) { //display error alert on form submit
					// App.scrollTo(error1, -200);
				},

				highlight: function (element) { // hightlight error inputs
					$(element)
						.closest('.form-group').addClass('has-error'); // set error class to the control group
				},

				unhighlight: function (element) { // revert the change done by hightlight
					$(element)
						.closest('.form-group').removeClass('has-error'); // set error class to the control group
				},

				success: function (label) {
					label
						.closest('.form-group').removeClass('has-error'); // set success class to the control group
				},

				submitHandler: function (form) {
					// Post-submit callback
					function showResponse (responseText, statusText) {
						if(responseText.code==0) {
							toastr.success("添加成功");
							$("#track_modal").modal('hide');
							table.fnClearTable(false);
							table.fnDraw();
						} else {
							toastr.error("添加失败");
						}
					}

					var options = {
						type:"post",
						url:"sale/clue_track",
						dataType:'json',
						success: showResponse,
					}

					track_form.ajaxSubmit(options);

				}
			});

    		var table = $("#clues_table").dataTable({
				"sPaginationType": "bootstrap",
		        // "aoColumnDefs": [
		        //     { 'bSortable': false, 'aTargets': [0] },
		        //     { "bSearchable": false, "aTargets": [ 0 ] }
		        // ],
		        "processing": true,
		        "bServerSide": true,
		        "sAjaxSource": "sale/clue_db",
		        // "sPaginationType": "full_numbers",
		        "iDisplayLength": 10,
		        "fnServerData": function (sSource, aoData, fnCallback) {
		            $.ajax
		            ({
		                'dataType': 'json',
		                'type': 'POST',
		                'url': sSource,
		                'data': aoData,
		                'success': fnCallback
		            });
		        },
		        "fnServerParams": function (aoData) {  
		             var serializedForm = $('#clue_search_form').serializeArray();
		             for (var n in serializedForm) {
		                var tmpobj = serializedForm[n];
		                var key = tmpobj['name'];
		                var value = tmpobj['value'];
		                aoData.push({"name":key,"value":value});
		             } 
		        }, 
		        "aaSorting": [
					[ 8, "desc" ],
					[ 12, "asc" ],
				],
		         "aoColumns": [
		            { "mData": "checkbox","bSortable":false },
		            { "mData": "student_name" },
		            { "mData": "student_no" },
		            { "mData": "parent_name1" },
		            { "mData": "trade_wish" },           
		            { "mData": "phone" },
		            { "mData": "school" },
		            { "mData": "grade" },
		            { "mData": "contact_times" },
		            { "mData": "nickname" },
		            { "mData": "last_contact_result" },
		            { "mData": "last_contact_date","bSearchable":false},
		            { "mData": "next_contact_date","bSearchable":false },
		            { "mData": "status" },
		            { "mData": "actions" },
		        ],
		        "fnDrawCallback": function( oSettings ) { // run some code on table redraw
		            App.initUniform($('input[type="checkbox"]', table));  // reinitialize uniform checkboxes on each table reload
		        }
		    });

			// 文件上传

			// Initialize the jQuery File Upload widget:
			$('#fileupload').fileupload({
				disableImageResize: false,
				autoUpload: true,
				acceptFileTypes:/(xls|xlsx|csv)$/i ,
				maxFileSize:20000000,
				//xhrFields: {withCredentials: true},
				//url: 'upload/do_upload?action=add&token=12321412',
				url:'sale/file_upload',
				progressall: function (e, data) {
					var progress = parseInt(data.loaded / data.total * 100, 10);
					$('#progress').show();
					$('#progress .progress-bar').css(
						'width',
						progress + '%'
					);

					$('#progress .progress-bar .sr-only').text(
						progress + '%'
					);

				},
				done: function (e, data) {
					console.log(data);

					$('#name').val(data.files[0].name)

					$('#progress .progress-bar .sr-only').text("上传完毕");
					$('#progress').removeClass('active');
					$('#progress').hide();
				}
			}).bind('fileuploadadd', function (e, data) {
				console.log(data);
				console.log(data.files.error);
				if(data.files.error){
					// $(this).parent().children("p").remove();
					// $(this).removeAttr("disabled");
					if(data.files[0].error=='File type not allowed'){
						//$(this).parent().append("<label class='error'>we类型错误</label>");
						console.log("文件类型错误");
					}
					if(data.files[0].error=='maxFileSize'){
						//$(this).parent().append("<label class='error'>图片不能大于2M</label>");
						alert("文件大小不能超过20M");
					}
				}
			});

            //查询
            $(document).on('click','#search_submit_btn',function(){
                if(table) {
                    table.fnClearTable(false);
                    table.fnDraw();
                }
            });

			// 转移
			$(document).on('click','#dist_submit_btn',function(){
				var ids = get_checkboxs(table);

				if(ids == '') {
					toastr.warning("请至少选择一项记录");
					return false;
				}

				var owner = $("#new_owner  option:selected").val();

				//ajax删除
				$.ajax({
					url: 'sale/clue_dist',
					type: 'POST',
					dataType: 'json',
					data: {ids: ids,owner:owner},
				})
					.done(function(responseText) {
						if(responseText.code==0){
							toastr.success(responseText.msg);
						} else {
							toastr.error(responseText.msg);
						}
					})
					.fail(function() {
					})
					.always(function() {
					});
			});

			$(document).on('click','#import_submit_btn',function(){
				var name = $("#name").val();

				App.blockUI({
					target: '#send_item_modal',
					overlayColor: 'none',
					message: '道具发送中,请勿关闭页面...',
					cenrerY: true,
					boxed: true
				});

				if(!name) {
					toastr.error("文件未上传成功,请重新上传");
					return;
				}

				App.blockUI({
					target: '#import_modal',
					overlayColor: 'none',
					message: '数据导入中,请稍候...',
					cenrerY: true,
					boxed: true
				});

				//ajax删除
				$.ajax({
					url: 'sale/clue_import',
					type: 'POST',
					dataType: 'json',
					data: {name:name},
				})
					.done(function(responseText) {
						App.unblockUI('#import_modal');

						if(responseText.code==0){
							toastr.success(responseText.msg);
							$("#import_modal").modal('hide');
						} else {
							toastr.error(responseText.msg);
						}
					})
					.fail(function() {
						App.unblockUI('#import_modal');
					})
					.always(function() {
					});
			});

			//清除弹窗原数据
			$("#import_modal").on("hidden.bs.modal", function() {
				$('#import_modal .fileinput-filename').text('');
				$('#name').val('').end();
			});

			// 追踪按钮
			$(document).on('click','.clue_track_btn',function(){
				var no = $(this).parents('tr').find('td').eq(1).text();
				var name = $(this).parents('tr').find('td').eq(2).text();
				var id = $(this).attr('data-pk');
				$('#student_id').val(id);
				$('#student_name').val(name+'('+no+')');

			});

            //重置
            $(document).on('click','#search_reset_btn',function(){
                form1[0].reset();
                if(table) {
                    table.fnClearTable(false);
                    table.fnDraw();
                }
            });

            // 切换显示
            $(document).on('click','#clue_search_btn',function(){
                $('#clue_search_well').toggle();
            });

			// 全选按钮事件
			jQuery('.group-checkable',table).change(function () {
				var set = jQuery(this).attr("data-set");
				var checked = jQuery(this).is(":checked");
				jQuery(set).each(function () {
					if (checked) {
						$(this).attr("checked", true);
						$(this).parents('tr').addClass("active");
					} else {
						$(this).attr("checked", false);
						$(this).parents('tr').removeClass("active");
					}
				});
				jQuery.uniform.update(set);
			});

			//
			$(document).on('click','#clue_dist_btn',function(e){
				var ids = get_checkboxs(table);
					if(ids != '') {
						$('input[name=clue_ids]','#clue_dist_from').val(ids);
					}
			});


			// 删除线索
			$(document).on("click", ".clue_del_btn", function(e) {
				var clue = $(this).parents("tr");
				//获取id
				var id = $(this).attr('data-pk');
				//获取title
				var name  = clue.children('td').eq(2).text();;

				bootbox.confirm("是否删除该条线索：<strong>"+name+"</strong>", function(result) {
					if(result!=null&&result!=false)
					{
						//ajax删除
						$.ajax({
							url: 'sale/clue_del',
							type: 'POST',
							dataType: 'json',
							data: {id: id},
						})
							.done(function(response) {
								if(response.code==0){
									toastr.success(response.msg);
									clue.remove();
								} else {
									toastr.error(response.msg);
								}
							})
							.fail(function() {
								console.log("error");
							})
							.always(function() {
								console.log("complete");
							});

					}
				});
			});


   		}
	};
}();   

